package org.inspiration.dudu.message.service.impl;

import lombok.RequiredArgsConstructor;
import org.inspiration.dudu.message.mapper.SessionMapper;
import org.inspiration.dudu.message.model.entity.SessionEntity;
import org.inspiration.dudu.message.model.vo.SessionVO;
import org.inspiration.dudu.message.service.SessionService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class SessionServiceImpl implements SessionService {

    private final SessionMapper sessionMapper;

    @Override
    public SessionVO transToVO(SessionEntity sessionEntity) {
        SessionVO sessionVO = new SessionVO();
        BeanUtils.copyProperties(sessionEntity, sessionVO);
        return sessionVO;
    }

    @Override
    public SessionEntity getSession(Long senderId, Long receiverId) {
        // 检查 session 是否存在
        SessionEntity sessionEntity = sessionMapper.find(senderId, receiverId);
        if (sessionEntity == null) {
            // 若不存在，创建新的 session
            sessionEntity = SessionEntity.builder()
                    .fromUserId(senderId)
                    .toUserId(receiverId)
                    .build();

            sessionEntity = sessionMapper.save(sessionEntity);
        }
        return sessionEntity;
    }

    @Override
    public void increaseUnreadCount(Long sessionId) {
        sessionMapper.increaseUnreadCount(sessionId);
    }

    @Override
    public List<SessionVO> getSessions(Long fromUserId, Integer pageNum, Integer pageSize) {
        return sessionMapper.getSessions(fromUserId, (pageNum - 1) * pageSize, pageSize);
    }
}
